<?php

namespace App\Http\Middleware;

use App\Services\Log;
use Exception;
use App\Exceptions\ApiException;
use  App\Models\UserTicket;
use Closure;
use Illuminate\Support\Facades\Input;

class ApiTicketVerify
{
    /**
     * Handle an incoming request
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws ApiException
     */
    public function handle($request, Closure $next)
    {
        try{
            $ticket = $request->input('ticket');
            $client_source = $request->input('ClientSource');
            $result = UserTicket::where([
                ['status','=',1],
                ['ticket','=',$ticket],
                ['client_source','=',$client_source]])->first();
          //   $result = check_ticket($ticket);
            if (!$result) {
                throw new ApiException('验证ticket失败',0);
            }
        } catch (Exception $e) {
//            $response->header('Access-Control-Allow-Origin', '*');
//            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, X-Requested-With');
//            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
//            $response->header('Access-Control-Allow-Credentials', false);
            if ($e instanceof ApiException)
            {
                throw $e;
            }
            else
            {
                throw new ApiException($e->getMessage(),$e->getCode(),$e);  
            }
        }
        return $next($request);
        
    }
}
